#include "device_file_browser.h"
#include "ui_device_file_browser.h"
#include <QDebug>
#include <QObject>
#include <QSettings>
#include <QMessageBox>
#include <QDesktopServices>
device_file_browser::device_file_browser(QWidget *parent) :
    device_mdle(parent),
    ui(new Ui::device_file_browser)
{
    ui->setupUi(this);
    this->hide_dev(true);
    //this->setVisible(true);
    tree = new QTreeViewMdTitle;
    ui->layout_page->addWidget(tree); //显示到目录
    // --------------------------------------------
    // 修改默认的界面信息
    table->setItem(1-1, 1-1, new QTableWidgetItem(QString("dev_name")));
    table->setItem(1-1, 2-1, new QTableWidgetItem(QString("device_file_browser")));
    table->setItem(2-1, 1-1, new QTableWidgetItem(QString("dev_code")));
    table->setItem(2-1, 2-1, new QTableWidgetItem(QString("00000001")));
    table->setItem(7-1, 1-1, new QTableWidgetItem(QString("dev_handle")));
    table->setItem(7-1, 2-1, new QTableWidgetItem(QString("device_file_browser1")));

    // --------------------------------------------
    // 重新编写IO
    table->setItem(1-1, 3-1, new QTableWidgetItem(QString("itf_in_num")));
    table->setItem(1-1, 4-1, new QTableWidgetItem(QString("0")));

    table->setItem(1-1, 5-1, new QTableWidgetItem(QString("itf_out_num")));
    table->setItem(1-1, 6-1, new QTableWidgetItem(QString("1")));
    table->setItem(2-1, 5-1, new QTableWidgetItem(QString("itf_out1")));
    table->setItem(2-1, 6-1, new QTableWidgetItem(QString("m_fil"))); //器件保留的IO信息，IO根据名字直接加载
    //注册IO的逻辑
    m_interface_fil = new interface_fil_master;
    connect(m_interface_fil,&interface_mdle::itf_out_tx,
            this,&device_mdle::itf_out1_tx);
    connect(this,&device_mdle::itf_out1_rx,
            m_interface_fil,&interface_mdle::itf_out_rx);
    //连接到监测器件
    connect(this,&device_mdle::itf_out1_tx,
            this,&device_mdle::signal_itf_monitor_slot);
    connect(this,&device_mdle::itf_out1_rx,
            this,&device_mdle::signal_itf_monitor_slot);

    //连接IO内部逻辑
    connect(m_interface_fil,&interface_fil_master::recv_fil_trig,
            this,&device_file_browser::wait_master_recv_slot);
    // --------------------------------------------
    // 增加工作目录，继承工作页面
    QSettings *settings;
    QString setting_ini = QApplication::applicationDirPath() + "/user_data/setting.ini";
    settings = new QSettings(setting_ini,QSettings::IniFormat);
    file_work_dir = settings->value("work_dir","").toString(); //获取当前目录
    //加载设备的同步目录，作为基础路径
    file_work_dir = file_work_dir + "/dev_workspace/fil_itf/"+this->getHandle();
    connect(tree,&QTreeViewMdTitle::load_trig,
            this,&device_file_browser::itf_fil_load_slot);
    connect(tree,&QTreeViewMdTitle::save_trig,
            this,&device_file_browser::itf_fil_save_slot);
    connect(tree,&QTreeViewMdTitle::list_trig,
            this,&device_file_browser::itf_fil_list_slot);


}

device_file_browser::~device_file_browser()
{
    delete ui;
}

void device_file_browser::itf_fil_save_slot(QStringList dir_info)
{
    // --------------------------------------------
    // 缓存文件
    if(dir_info.at(1) != "") //大小不为空，说明是文件
    {
        QString save_name;
        for(int i = 2; i < dir_info.size() - 1; i++)
        {
            save_name.append(dir_info.at(i));
            save_name.append("/");
        }
        if(dir_info.size() - 2 > 0)
        {
            save_name.append(dir_info.at(dir_info.size() - 1)); //加载文件
            save_name.append(".bit"); //加载文件
            m_interface_fil->master_send_save(file_work_dir,save_name); //发起缓存请求
            return; //正确处理完成文件
        } else
        {
            QMessageBox::warning(this,"file_exist",
                                 "file not exist, please load first",
                                 QMessageBox::Cancel);
            return;
        }

    }

    // --------------------------------------------
    // 加载目录，以及文件信息的支撑，
    // 设置文件过滤器，只显示指定类型的文件
    QString filter = "bit (*.bit);;all (*)";
    // 弹出打开文件对话框
    QString fileSrc = QFileDialog::getOpenFileName(
        this,                  // 父窗口
        "选择文件",            // 对话框标题
        QApplication::applicationDirPath(),      // 初始目录（家目录）
        filter                 // 文件过滤器
    );
    QRegExp hexRegExp("^[0-9a-fA-F]{8}$");

    if(fileSrc.isEmpty())
    {
        QDEBUG << fileSrc << "is error";
    }
    // --------------------------------------------
    // 合成相对路径
    QString basename;
    for(int i = 2; i < dir_info.size(); i++)
    {
        basename.append(dir_info.at(i));
        basename.append("/");
    }
    //basename.append(dir_info.at(0)); 缓存信息不带文件名
    //basename.append(".bit"); //所有文件都按照bit文件处理
    QFileInfo finfo(fileSrc);
    int lastPos = finfo.baseName().lastIndexOf('_');
    QString srcName = lastPos == -1 ? "" : finfo.baseName().mid(lastPos+1);
    basename.append(srcName); //加载文件
    basename.append(".bit"); //加载文件
    if(hexRegExp.exactMatch(srcName) == 0) //
    {
        QDEBUG << finfo.baseName() << "must like _00112233.bit";
        QMessageBox::critical(this, "错误", "file name must like _00112233", QMessageBox::Close);
        return;
    }
    //复制文件到基准目录+相对路径
    QDir  dir  = QDir(file_work_dir);
    if (!dir.exists())
    {
        QDEBUG << file_work_dir << "not exist";
    }
    QString fileDst = dir.filePath(basename);
    copyFile(fileSrc,fileDst);
    m_interface_fil->master_send_save(file_work_dir,basename); //发起缓存请求

}

bool device_file_browser::copyFile(const QString &sourceFilePath, const QString &destFilePath)
{
    m_lastError = "";

    // 检查源文件是否存在
    if (!QFile::exists(sourceFilePath)) {
        m_lastError = QString("源文件不存在: %1").arg(sourceFilePath);
        return false;
    }

    // 如果源文件和目标文件相同，无需复制
    if (QFileInfo(sourceFilePath) == QFileInfo(destFilePath)) {
        m_lastError = "源文件和目标文件相同";
        return false;
    }

    // 如果目标文件存在，则先删除
    if (QFile::exists(destFilePath)) {
        if (!QFile::remove(destFilePath)) {
            m_lastError = QString("无法删除现有目标文件: %1").arg(destFilePath);
            return false;
        }
    }

    // 确保目标文件所在目录存在
    QFileInfo destFileInfo(destFilePath);
    QDir destDir = destFileInfo.dir();
    if (!destDir.exists() && !destDir.mkpath(".")) {
        m_lastError = QString("无法创建目标目录: %1").arg(destDir.path());
        return false;
    }

    // 执行文件复制
    if (!QFile::copy(sourceFilePath, destFilePath)) {
        m_lastError = "copy error";
        return false;
    }

    return true;
}

void device_file_browser::itf_fil_load_slot(QStringList dir_info)
{
    // --------------------------------------------
    // 合成相对路径
    QString basename;
    for(int i = 2; i < dir_info.size(); i++)
    {
        basename.append(dir_info.at(i));
        basename.append("/");
    }
    basename.append(dir_info.at(0));
    basename.append(".bit"); //所有文件都按照bit文件处理

    m_interface_fil->master_send_load(file_work_dir,basename); //发起缓存请求

}

void device_file_browser::itf_fil_list_slot(QStringList)
{
    m_interface_fil->master_send_list(); //发送目录更新申请
}

void device_file_browser::wait_master_recv_slot(itf_fil)
{
    if(m_interface_fil->get_recv_fil_type() == "list")
    {
        QStringList md_title = m_interface_fil->master_recv_list();
        QDEBUG << QDEBUG_WITH_PARAM( md_title );
        tree->get_markdown_title_tree(md_title.join("\n")); //换行成文本方便目录解析
        tree->scan_delet_same_item();
    } else if(m_interface_fil->get_recv_fil_type() == "save")
    {
        QString basename = m_interface_fil->master_recv_save(file_work_dir);
        tree->add_file_title_tree(basename);
        tree->scan_delet_same_item();
    }
    else if(m_interface_fil->get_recv_fil_type() == "load")
    {
        QString basename = m_interface_fil->master_recv_load(file_work_dir);
        // 将文件路径转换为QUrl对象
        QDir baseDir(file_work_dir);
        QString s_file = baseDir.filePath(basename);
        QUrl fileUrl = QUrl::fromLocalFile(s_file);
        // 尝试打开文件
        if (QDesktopServices::openUrl(fileUrl) == false)
        {
            qDebug() << "无法打开文件。" << fileUrl;
            //如果打不开目标日志文件
        }
    }

}

